#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 06.11.2010
Copyright (C) 2010 Alexander S. Razzhivin ( site http://httpbots.com )

#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from pyvkapi import PyVkApi
import os
import urllib, urllib2, re

def download_record(dest_dir, r, reporthook):
  info = ""
  path = os.path.abspath(os.path.join(dest_dir,r['artist']))
  if not os.path.exists(path):
    os.makedirs(path)
  
  file = os.path.abspath(os.path.join(path,r['title'])) + ".mp3"
  if not os.path.exists(file):
    try:
      urllib.urlretrieve(r['url'], file, reporthook)
    except IOError:
      info = 'File save error. File name too long'
  else:
    info = "--OK--"
  return info
      
def download_mp3s(dest_dir, records):
  for r in records:
    print r['title'], ' ',
    info = download_record(dest_dir, r, reporthook_console)
    print info

LAST_PERCENT_DOWN = -1

def report(count, blockSize, totalSize):
  global LAST_PERCENT_DOWN
  result = ""
  percent_down = (count*blockSize) * 100 / totalSize
   
  if not (percent_down % 10) and not (LAST_PERCENT_DOWN == percent_down):
    result = str(percent_down)
    LAST_PERCENT_DOWN = percent_down
  return result
    
def reporthook_console(count, blockSize, totalSize):
  r = report(count, blockSize, totalSize)
  if r: print r,
  
def check_updates(version):
    '''
    @return: (version, link)
    '''
    data = ""
    pat = '''"vkag_([0-9]{2})" href="http://([\w\d:#@%/;$()~_?\+-=\\\.& ]*)["|']'''
    try:
      data=urllib2.urlopen("http://httpbots.com/ru/content/proekt-vk-audio-grabber").read()
    except:
      print "Проблема при загрузке страницы с обновлениями"
      
    vers_links = re.findall(pat, data)
    for v, l in vers_links:
      if  int(v) > int(version):
        return (v,l)

def main():
  vkapi = PyVkApi(email='test@test.com', password='', uid='1587648', api_id='2006539')
  
  records = vkapi.call(['method=audio.get'])
  download_mp3s('/home/ranux/Data/Media/Music/downloaded/', records)
  # print check_updates('30')

  
if __name__ == '__main__':
  main()